package com.qinghuan.threads.chapterOne;

/**
 * @Author: dubao
 * @Date: 2022/5/16 19:34
 * @Description:
 * 当前线程调用共享变量的wait()方法后只会释放当前共享变量上的锁，
 * 如果当前线程还持有其他共享变量的锁，则这些锁是不会被释放的
 */
public class Test1_3 {

    private static volatile Object resourceA = new Object();
    private static volatile Object resourceB = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    synchronized (resourceA) {
                        System.out.println("A running");

                        synchronized (resourceB) {
                            System.out.println("B running");
                            //线程A阻塞，并释放获取到的resourceA的锁
                            System.out.println("ThreadA release resourceA lock");

                            resourceA.wait();
                            resourceB.wait();//上一行的wait()方法执行后就直接退出该线程了，这一行未执行
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        //创建线程
        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    synchronized (resourceA) {
                        System.out.println("threadB get resourceA lock");
                        System.out.println("threadB try get resource lock...");
                        //获取resourceB共享资源的监视器锁
                        synchronized (resourceB) {
                            System.out.println("threadB get resourceB lock");

                            //线程B阻塞，并释放获取到的resourceA的锁
                            System.out.println("threaadB release resourceA lock");
                            resourceA.wait();
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        //启动线程
        threadA.start();
        threadB.start();
        //等待两个线程结束
        threadA.join();
        threadB.join();
        System.out.println("main over");
    }

}
